#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Date: 2020/9/28

from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
from django.contrib.auth.models import User


class UserSerializer(serializers.ModelSerializer):
    # 此字段将被序列化为关联对象的主键。属性使用related_name的值，如果没有则使用关联类小写_set(snippet_set)
    # snippets = serializers.PrimaryKeyRelatedField(many=True,
    # queryset=Snippet.objects.all())
    # 此字段将被序列化为关联对象的字符串表示方式（即模型类__str__方法的返回值）
    # snippets = serializers.StringRelatedField()
    snippets = serializers.HyperlinkedRelatedField(many=True,
                                                   view_name='snippet-detail',
                                                   read_only=True)
    url = serializers.HyperlinkedIdentityField(view_name='user-detail',
                                               lookup_field='username')
    
    class Meta:
        model = User
        fields = ('url', 'id', 'email', 'username', 'snippets')
        # fields = '__all__'


# TODO： 这里继承serializers.ModelSerializer也可用
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    # owner = UserSerializer()
    # TODO: 这里是想改变默认字段，默认为pk, 现在想改为code, 未成功（上面的username以成功, unique的问题？）
    # code = serializers.HyperlinkedIdentityField(view_name='snippet-code',
    #                                             lookup_field='code')
    
    highlight = serializers.HyperlinkedIdentityField(
        view_name='snippet-highlight', format='html')
    
    class Meta:
        model = Snippet
        fields = (
            'url', 'highlight', 'owner', 'id', 'title', 'code', 'linenos',
            'language', 'style')

# class SnippetsListSerializer(serializers.List)